<?php

session_start();
include_once("../../untils/conn.php");
mysqli_query($con, "set names utf8");

// 获取当前正在登录的账号信息的代理
$proxy_acc = $_SESSION["account"];

// 防止 SQL 注入攻击
$proxy_acc = mysqli_real_escape_string($con, $proxy_acc);

// 查询 proxy 表，找到符合条件的数据并输出给前端
$sql = "SELECT * FROM proxy WHERE proxy_acc = '$proxy_acc'";

$result = mysqli_query($con, $sql);
if ($result) {
  $rows = mysqli_fetch_assoc($result);
  $id = $rows["proxy_id"];
  
  // 防止 SQL 注入攻击
  $id = mysqli_real_escape_string($con, $id);
  
  // 查询 proxy 表，根据 proxy_upid 来查找数据并将数据存储在数组中
  $sql = "SELECT proxy_id, proxy_acc FROM proxy WHERE proxy_upid = '$id'";
  $result = mysqli_query($con, $sql);
  if ($result) {
    $proxyIds = array();
    $proxyAccounts = array();

    // 循环遍历数据并将每个 proxy_id 和 proxy_acc 存储在数组中
    while($row = mysqli_fetch_assoc($result)) {
      $proxyIds[] = $row['proxy_id'];
      $proxyAccounts[$row['proxy_id']] = $row['proxy_acc'];
    }

    // 添加当前代理的 proxy_id 和 proxy_acc 到数组中
    $proxyIds[] = $id;
    $proxyAccounts[$id] = $proxy_acc;

    // 将代理ID数组转换为逗号分隔的字符串
    $proxyIdsStr = implode(",", $proxyIds);

    // 查询 order 表，根据 proxy_id 来查找数据并将数据存储在数组中
    $sql = "SELECT * FROM oder WHERE proxy_id IN ($proxyIdsStr)";
    $result = mysqli_query($con, $sql);
    if ($result) {
      $data = array();

      // 循环遍历数据并将每条数据存储在一个数组中
      while($row = mysqli_fetch_assoc($result)) {
        $oderid = $row['oderid'];
        $goods = $row['goods'];
        $name = $row['name'];
        $phone = $row['phone'];
        $card_sta = $row['card_sta'];
        $oder_sta = $row['status'];
        $notes = $row['beizhu'];
        $dn_time = $row['time'];
        $timestamp = date('Y-m-d H:i:s', $dn_time);

        $proxy_id = $row['proxy_id'];
        $account = $proxyAccounts[$proxy_id];

        $data[] = array(
          "order_id" => $oderid,
          "goods_name" => $goods,
          "account" => $account,
          "name" => $name,
          "phone" => $phone,
          "card_sta" => $card_sta,
          "order_sta" => $oder_sta,
          "notes" => $notes,
          "order_time" => $timestamp
        );
      }

      // 将数据转换为 JSON 格式并输出到前端
      echo json_encode($data);
    } else {
      // 输出错误信息到前端
      echo "查询失败，请稍后重试！";
    }
  } else {
    // 输出错误信息到前端
    echo "查询失败，请稍后重试！";
  }
} else {
  // 输出错误信息到前端
  echo "查询失败，请稍后重试！";
}

// 关闭数据库连接
mysqli_close($con);
